package com.example.jedis.client.protocol.response;

import com.example.jedis.client.protocol.constant.RedisProtocolConstant;
import com.example.jedis.client.transport.RedisTransport;
import com.example.jedis.client.utils.RedisProtocolUtils;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

public abstract  class AbstractApplyProtocol implements  ApplyProtocol {

    /*public String readFirstSegment(RedisTransport redisTransport, ByteBuffer byteBuffer){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte lastByte = 0;
        while( true){
            if(!byteBuffer.hasRemaining()){
                redisTransport.read(byteBuffer);
            }
            if(byteArrayOutputStream.size() > RedisProtocolConstant.ERROR_APPLY_MAX_SIZE){
                throw new JedisException("ApplyError :message to large:"+ RedisProtocolUtils.getStringFromBytes(byteArrayOutputStream));
            }
            byte b = byteBuffer.get();
            if(lastByte == RedisProtocolConstant.CR_BYPE && b == RedisProtocolConstant.LF_BYTE){
                String value = RedisProtocolUtils.getStringFromBytes(byteArrayOutputStream);
                return value;
            }
            lastByte = b;
            byteArrayOutputStream.write(b);
        }
    }*/

    /**
     * 取第一段数据 \r\n之前的，包含 \r\n
     * @param redisTransport
     * @param byteBuffer
     * @return
     */
    private byte [] readFirstSegment(RedisTransport redisTransport, ByteBuffer byteBuffer,int size){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte lastByte = 0;
        while( true){
            if(!byteBuffer.hasRemaining()){
                byteBuffer.clear();
                redisTransport.read(byteBuffer);
            }
            byte b = byteBuffer.get();
            byteArrayOutputStream.write(b);
            if(lastByte == RedisProtocolConstant.CR_BYPE && b == RedisProtocolConstant.LF_BYTE && byteArrayOutputStream.size()> size){
                return byteArrayOutputStream.toByteArray();
            }
            lastByte = b;
        }
    }

    public String readFirstSegmentToString(RedisTransport redisTransport, ByteBuffer byteBuffer){
        byte [] data = readFirstSegment(redisTransport,byteBuffer,-1);
        return RedisProtocolUtils.getStringFromBytes(data,0 ,data.length-2);
    }

    public String readFirstSegmentToString(RedisTransport redisTransport, ByteBuffer byteBuffer,int size){
        byte [] data = readFirstSegment(redisTransport,byteBuffer,size);
        return RedisProtocolUtils.getStringFromBytes(data,0 ,data.length-2);
    }

    public int readFirstSegmentToInt(RedisTransport redisTransport, ByteBuffer byteBuffer){
        byte [] data = readFirstSegment(redisTransport,byteBuffer,-1);
        return RedisProtocolUtils.getIntFromBytes(data,0 ,data.length-2);
    }


}
